﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Web.UI.WebControls;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;
using Cms.Web.Framework.Controls;
using Cms.Web.Framework.Plugins.Attributes;
using iLib.Web.UI.WebControls;
using Content = Cms.Domain.Content;
using SortDirection = Cms.Domain.SortDirection;

namespace Cms.Web.Framework.Plugins
{
    public class ListContent : BaseTemplatedPlugin
    {
        // Property fields
        private int _categoryID;
        private string _publishedDateFormat;
        private ListContentReadMoreMode _readMoreMode;
        private string _readMorePage;
        private int _returnCount;
        private int _skipFirstCount;
        private SortDirection _sortDirection;
        private ContentSortMode _sortMode;
        private bool _truncateAtPageBreak;

        // Template controls
        private iRepeater rpContent;
        private LocalizedPluginLiteral lplReadMore;

        [Enumeration("Categories", true)]
        public int CategoryID
        {
            get { return _categoryID; }
            set { _categoryID = value; }
        }
        
        [Enumeration("ContentSortMode", true)]
        public ContentSortMode SortMode
        {
            get { return _sortMode; }
            set { _sortMode = value; }
        }

        [Enumeration("SortDirections", true)]
        public SortDirection SortDirection
        {
            get { return _sortDirection; }
            set { _sortDirection = value; }
        }
        
        public int SkipFirstCount
        {
            get { return _skipFirstCount; }
            set { _skipFirstCount = value; }
        }

        public int ReturnCount
        {
            get { return _returnCount; }
            set { _returnCount = value; }
        }
        
        public string PublishedDateFormat
        {
            get { return _publishedDateFormat; }
            set { _publishedDateFormat = value; }
        }
        
        [Browse("file")]
        public string ReadMorePage
        {
            get { return _readMorePage; }
            set { _readMorePage = value; }
        }
        
        [Enumeration("ListContentReadMoreModes", true)]
        public ListContentReadMoreMode ReadMoreMode
        {
            get { return _readMoreMode; }
            set { _readMoreMode = value; }
        }

        public bool TruncateAtPageBreak
        {
            get { return _truncateAtPageBreak; }
            set { _truncateAtPageBreak = value; }
        }

        [Enumeration("ReadMoreVisibilityMode", true)]
        public ReadMoreVisibilityMode ReadMoreVisibility { get; set; }

        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                rpContent = (iRepeater)FindControl("rpContent");
                lplReadMore = (LocalizedPluginLiteral)FindControl("lplReadMore");
                rpContent.ItemDataBound += rpContent_ItemDataBound;
                rpContent.DataSource = GetContent();
                rpContent.DataBind();
            }
            catch (Exception ex)
            {
                Logging.LogError("ListContent", ex);
                Controls.Clear();
            }
        }

        protected IList<Content> GetContent()
        {
            ICategoryRepository categoryRepository = new CategoryRepository();
            var category = categoryRepository.GetCategory(_categoryID);
            IContentRepository contentRepository = new ContentRepository();
            SearchContentFilter filter = new SearchContentFilter(string.Empty)
                                             {
                                                 LocaleId = RequestDetails.Locale.ID,
                                                 CategoryId = _categoryID,
                                                 SortMode = _sortMode,
                                                 SortDirection = _sortDirection
                                             };
            return contentRepository.ListContent(filter, _skipFirstCount, _returnCount, category.GetAllIDs());
        }
        
        protected void rpContent_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var content = (Content)e.Item.DataItem;
            var pnlContent = (Panel)e.Item.FindControl("pnlContent");
            var litName = (Literal)e.Item.FindControl("litName");
            var litTitle = (Literal)e.Item.FindControl("litTitle");
            var litPublishedBy = (Literal)e.Item.FindControl("litPublishedBy");
            var litPublishedDate = (Literal)e.Item.FindControl("litPublishedDate");
            var hlReadMore = (HyperLink)e.Item.FindControl("hlReadMore");
            var litAnchor = (Literal)e.Item.FindControl("litAnchor");
            bool contentIsTruncated = false;
            if (hlReadMore != null && lplReadMore != null)
            {
                hlReadMore.Text = lplReadMore.Text;
            }
            if (litName != null)
            {
                litName.Text = content.Name;
            }
            if (pnlContent != null)
            {
                string html = content.GetPublishedHtml(RequestDetails.Locale.ID);
                if (_truncateAtPageBreak)
                {
                    contentIsTruncated = Content.ContainsPageBreak(html);
                    html = Content.TruncateAfterPageBreak(html);
                }
                ContentParser.Parse(html, pnlContent, RequestDetails.RequestedUrl);
            }
            if (litTitle != null)
            {
                litTitle.Text = content.GetPublishedTitle(RequestDetails.Locale.ID);
            }
            if (litPublishedBy != null)
            {
                litPublishedBy.Text = content.CreatedBy.Fullname;
            }
            if (litPublishedDate != null)
            {
                DateTime publishedDate = content.FirstPublished.HasValue
                                             ? content.FirstPublished.Value
                                             : content.Created;
                litPublishedDate.Text = !string.IsNullOrEmpty(_publishedDateFormat)
                                            ? publishedDate.ToString(_publishedDateFormat, Thread.CurrentThread.CurrentCulture.DateTimeFormat)
                                            : publishedDate.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat);
            }
            if (hlReadMore != null && !string.IsNullOrEmpty(_readMorePage))
            {
                if (_readMoreMode == ListContentReadMoreMode.Bookmark)
                {
                    hlReadMore.NavigateUrl = "~/" + _readMorePage + "#lc" + content.ID;
                }
                else
                {
                    hlReadMore.NavigateUrl = "~/" + _readMorePage + "?ContentID=" + content.ID;
                }
                if (ReadMoreVisibility == ReadMoreVisibilityMode.OnlyVisibleWhenContentIsTruncated && !contentIsTruncated)
                {
                    hlReadMore.Visible = false;
                }
            }
            if (litAnchor != null)
            {
                litAnchor.Text = "<a name=\"lc" + content.ID + "\" />";
            }
        }
    }
}